/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>





int main(int argc, char *argv[])
{
     int sockfd, newsockfd, portno, clilen;
     char buffer[5000];
     struct sockaddr_in serv_addr, cli_addr;
     int n;

     if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         return 0;
     }
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
       fprintf(stderr,"ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0) 
       fprintf(stderr,"ERROR on binding");
     listen(sockfd,5);
     clilen = sizeof(cli_addr);

     while(1){
       newsockfd = accept(sockfd, 
			  (struct sockaddr *) &cli_addr, 
			  &clilen);
       if (newsockfd < 0) 
	 fprintf(stderr,"ERROR on accept");


       bzero(buffer,5000);
       n = read(newsockfd,buffer,5000);
       if (n < 0) fprintf(stderr,"ERROR reading from socket");
       
       printf("%s\n",buffer);

       n = write(newsockfd,"peers 04fc60a1f10d0b2bdbea55451cfaae8a [127.0.0.1:10012 127.0.0.1:10013]",strlen("peers 5ce2de06b995755c8b29126748ce01a2 [127.0.0.1:10015 127.0.0.1:10013]"));
       if (n < 0) fprintf(stderr,"ERROR writing to socket");
     }
     return 0; 
}
